package com.fresh.auth0;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import com.fresh.auth0.algorithms.Algorithm;
import com.fresh.auth0.exceptions.InvalidClaimException;
import com.fresh.auth0.exceptions.JWTCreationException;
import com.fresh.auth0.exceptions.JWTVerificationException;
import com.fresh.auth0.interfaces.Claim;
import com.fresh.utils.DateTimeUtil;

public class TokenGenerator {

	private static final String secret="secret"; 
	private static final String issuer="issuer"; 
	private static final int expireHours=12*6;//3小时过期
	
	public static Token create(Map<String, Object> claims) throws IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		String tokenString= JWT.create().withIssuer(issuer).withExpiresAt(DateTimeUtil.addHours(DateTimeUtil.getSystemDate(), expireHours))
				.withClaim(claims).sign(Algorithm.HMAC256(secret));
		return new Token(tokenString,expireHours*60);
	}
	
	public static String create(int expiresAt, Map<String, Object> claims) throws IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		return JWT.create().withIssuer(issuer).withExpiresAt(DateTimeUtil.addSeconds(DateTimeUtil.getSystemDate(), expiresAt))
				.withClaim(claims).sign(Algorithm.HMAC256(secret));
	}
	
	public static Claim getClaim(String token,String claim) throws IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		return JWT.decode(token).getClaim(claim);
	}
	
	public static boolean isExpired(String token) throws JWTVerificationException, IllegalArgumentException, UnsupportedEncodingException {
		try {
			return DateTimeUtil.compareTwoDate(DateTimeUtil.getSystemDate(), JWT.require(Algorithm.HMAC256(secret)).withIssuer(issuer).build().verify(token).getExpiresAt()) < 0 ? true : false;
		} catch (InvalidClaimException e) {
			e.printStackTrace();
			return true;
		}
	}
	
	public static String create(String secret, String issuer, int expiresAt, Map<String, Object> claims) throws IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		return JWT.create().withIssuer(issuer).withExpiresAt(DateTimeUtil.addSeconds(DateTimeUtil.getSystemDate(), expiresAt))
				.withClaim(claims).sign(Algorithm.HMAC256(secret));
	}

	public static boolean isExpired(String secret, String issuer, String token) throws JWTVerificationException, IllegalArgumentException, UnsupportedEncodingException {
		return DateTimeUtil.compareTwoDate(DateTimeUtil.getSystemDate(), JWT.require(Algorithm.HMAC256(secret)).withIssuer(issuer).build().verify(token).getExpiresAt()) > 0 ? true : false;
	}

}
